package com.sys.sprinngboot.goodtheater.controller;

import com.sys.sprinngboot.goodtheater.bean.User;
import com.sys.sprinngboot.goodtheater.constant.Role;
import com.sys.sprinngboot.goodtheater.service.UserService;
import com.sys.sprinngboot.goodtheater.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @ResponseBody
    @PostMapping("/doLogin")
    public Msg login(@RequestParam("email") String email,
                     @RequestParam("password") String password, Model model, HttpSession httpSession){
        System.out.println("用户login");
        System.out.println(email+password);
        User userByEmail = userService.userByEmail(email);
        System.out.println(userByEmail);
        if(userByEmail != null){
            if(password.equals(userByEmail.getPassword())){
                httpSession.setAttribute("login",userByEmail);
                return Msg.success().add("msg", "成功登录！");
            }
        }
        model.addAttribute("msg","用户名或者密码错误");
        return Msg.fail().add("msg","用户名或者密码错误");
    }

    @PostMapping("/doRegister")
    public String register(@RequestBody User user, Model model){
        //System.out.println(user);
        //前后端的校验User
        System.out.println(user);
        User user1 = userService.userByEmail(user.getEmail());
        if(user1 != null){
            System.out.println("邮箱已被占用");
            model.addAttribute("registerMsg" , "邮箱已被占用");
            return "register";
        }
        user.setRole(Role.USER);
        userService.saveUser(user);
        System.out.println("注册成功");
        model.addAttribute("registerMsg" , "注册成功");
        return "login";
    }

    @GetMapping("/login")
    public String toLoginPage(){
        System.out.println("login");
        return"login";
    }

    @GetMapping("/register")
    public String toRegisterPage(){
        System.out.println("register");
        return "register";
    }
}
